#pragma once
#include <iostream>
#include <cstring>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <wait.h>
#include <memory>
#include "Log.hpp"
#include "InetAddr.hpp"
const static int gport = 8888;
const static int gsock = -1;
const static int gblcklog = 8;
namespace socket_ns
{
    class Socket;
     using namespace log_ns;
    using SockSPtr = std::shared_ptr<Socket>;
    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void CreateBindOrDie(uint16_t port) = 0;
        virtual void CreateListenOrDie(int backlog=gblcklog) = 0;
        virtual SockSPtr Accepter(InetAddr *cliaddr) = 0;
        virtual bool Conntector(const std::string &peerip,uint16_t peerport) = 0;
        virtual int sockfd()=0;
        virtual void close()=0;
        virtual ssize_t Recv(std::string *out)=0;
        virtual ssize_t Send(const std::string &in)=0;

    public:
        void BuildListenSocket(uint16_t port)
        {
            CreateSocketOrDie();
            CreateBindOrDie(port);
            CreateListenOrDie();

        }
        bool BuidClientSocket(const std::string &peerip,uint16_t peerport)
        {
            CreateSocketOrDie();
            return Conntector(peerip,peerport);
        }
    };
    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR
    };
   
    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
        {

        }
        TcpSocket(int sockfd) : _sockfd(sockfd)
        {
        }
        ~TcpSocket()
        {
         

        }

        void CreateSocketOrDie() override
        {
            // 1.创建套接字
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0); // 第一个参数是证明他是tcp，证明他是面链接，向链接就是套接字不可以直接进行对话而是需要创建链接再来进行对话
            if (_sockfd < 0)
            {
                exit(SOCKET_ERROR);
                LOG(FATAL, "socket creat error\n");
            }
            LOG(INFO, "socket create success,sockfd %d\n", _sockfd);
        }
        void CreateBindOrDie(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;//使用来区分ipv4和ipv6的
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY; // 绑定ip地址为0；
            // 2.绑定
            if (::bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                LOG(FATAL, "bind error\n");
                exit(BIND_ERROR);
            }

            LOG(INFO, "bind success\n");
        }
        void CreateListenOrDie(int backlog = gblcklog) override
        {
            if (::listen(_sockfd, backlog) < 0)
            {
                LOG(FATAL, "listen error\n");
                exit(LISTEN_ERROR);
            }
            else
                LOG(INFO, "listen success\n");
        }
        SockSPtr Accepter(InetAddr *cliaddr) override
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 4获取新链接          招客店员
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&client, &len);
            if (sockfd < 0) // 提供服务的人员
            {
                LOG(FATAL, "accept error\n");
                return nullptr;
                // 这里不应该退出就像张三在揽客失败后会重新去揽客
            }
            *cliaddr = InetAddr(client);
            LOG(INFO, "get a new link ,client info: %s \n", cliaddr->AddrStr().c_str());
            return std::make_shared<TcpSocket>(sockfd);
        }
        bool Conntector(const std::string &peerip,uint16_t peerport) override
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(peerport);
            ::inet_pton(AF_INET, peerip.c_str(), &server.sin_addr); // 这个函数就是将IP地址转化为网络状态
            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                std::cerr << "connect socket error" << std::endl;
                return false;
            }
            return true;

        }
        int sockfd()
        {
            return _sockfd;
        }
        void  close()
        {
            if(_sockfd>0)
            {
                ::close(_sockfd);
            }

        }
        ssize_t Recv(std::string *out)override
        {
             //这里是流字节流  tcp 可以直接使用流的接口来使用
             char inbuffer[4096];
             ssize_t n=::recv(_sockfd,inbuffer,sizeof(inbuffer)-1,0);//店内的人元就像是一个管文件，从中读取 rcv
             //这里建立了链接就像管道中读取
          
             if(n>0)//成功夺取
             {
                inbuffer[n]=0;
                *out+=inbuffer;

            }
            return n;

        }
        ssize_t Send(const std::string &in)override
        {
            return ::send(_sockfd,in.c_str(),in.size(),0);


        }

    private:
        int _sockfd;
    };

}